﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.ComponentModel;
using System.IO;

namespace SanctusSoftware.CcliSongSelectLib
{

    public class SongSelectDocument : INotifyPropertyChanged
    {

        #region Events

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion

        #region Constants/Readonly

        public const string KeyValuePattern = @"(?<Key>[A-Za-z]+)=(?<Value>.*)";
        public const string CcliNumberPattern = @"[[]S A(?<Number>\d+)[]]";

        #endregion

        #region Properties

        private readonly Dictionary<string, string> _Dictionary = new Dictionary<string, string>();
        public Dictionary<string, string> Dictionary
        {
            get { return _Dictionary; }
        }

        #endregion

        #region Properties (USR Fields)

        public string Type
        {
            get { return GetValueOrEmpty("Type"); }
        }

        public string Version
        {
            get { return GetValueOrEmpty("Version"); }
        }

        public string Title
        {
            get { return GetValueOrEmpty("Title"); }
        }

        public string Author
        {
            get { return GetValueOrEmpty("Author"); }
        }

        public string AuthorFormatted
        {
            get { return string.Join("; ", this.AuthorList); }
        }
        public string[] AuthorList
        {
            get { return GetSplitOrEmpty("Author", '|'); }
        }

        public string Copyright
        {
            get { return GetValueOrEmpty("Copyright"); }
        }

        public string CopyrightFormatted
        {
            get { return string.Join("; ", CopyrightList); }
        }

        public string[] CopyrightList
        {
            get { return GetSplitOrEmpty("Copyright", '|'); }
        }

        public string Admin
        {
            get { return GetValueOrEmpty("Admin"); }
        }

        public string AdminFormatted
        {
            get { return string.Join("; ", AdminList); }
        }

        public string[] AdminList
        {
            get { return GetSplitOrEmpty("Admin", @"/t"); }
        }

        public string Themes
        {
            get { return GetValueOrEmpty("Themes"); }
        }

        public string ThemesFormatted
        {
            get { return string.Join(", ", ThemesList); }
        }

        public string[] ThemesList
        {
            get { return GetSplitOrEmpty("Themes", @"/t"); }
        }

        public string Keys
        {
            get { return GetValueOrEmpty("Keys"); }
        }

        public string Fields
        {
            get { return GetValueOrEmpty("Fields"); }
        }

        public string[] FieldsList
        {
            get { return GetSplitOrEmpty("Fields", @"/t"); }
        }

        public string Words
        {
            get { return GetValueOrEmpty("Words"); }
        }

        public string[] WordsList
        {
            get { return GetSplitOrEmpty("Words", @"/t"); }
        }

        public string CcliNumber
        {
            get { return GetValueOrEmpty("CcliNumber"); }
        }

        private readonly SongPartCollection _SongParts = new SongPartCollection();

        public SongPartCollection SongParts
        {
            get { return _SongParts; }
        }

        #endregion

        #region Methods

        public void Load(string path)
        {
            LoadString(File.ReadAllText(path));
        }

        public void LoadString(string text)
        {

            foreach (string key in Dictionary.Keys)
            {
                Dictionary.Remove(key);
                OnPropertyChanged(key);
                OnPropertyChanged(key + "List");
            }

            SongParts.Clear();

            foreach (string line in text.Split(new string[] { "\r\n" }, StringSplitOptions.None))
            {
                if (!TryAddKeyValue(line))
                {
                    TryAddCcliNumber(line);
                }

            }

            if (Dictionary.ContainsKey("Fields") && Dictionary.ContainsKey("Words"))
            {
                if (FieldsList.Length != WordsList.Length)
                {
                    // TODO: BOOM!
                }

                for (int i = 0; i < FieldsList.Length; i++)
                {
                    string field = FieldsList[i];
                    string words = WordsList[i];
                    string wordsFormatted = words.Replace(@"/n", System.Environment.NewLine).Trim();
                    SongParts.Add(new SongPart() { Name = field, Words = wordsFormatted });
                }
            }


        }


        private bool TryAddKeyValue(string line)
        {
            Match match = Regex.Match(line, KeyValuePattern);
            if (match != null && match.Value.Length > 0)
            {
                string key = match.Groups["Key"].Value;
                string value = match.Groups["Value"].Value;
                Dictionary.Add(key, value);
                OnPropertyChanged(key);
                OnPropertyChanged(key + "List");
                return true;
            }
            return false;
        }

        private void TryAddCcliNumber(string line)
        {
            Match match = Regex.Match(line, CcliNumberPattern);
            if (match != null && match.Value.Length > 0)
            {
                string key = "CcliNumber";
                string value = match.Groups["Number"].Value;
                Dictionary.Add(key, value);
                OnPropertyChanged(key);
            }
        }


        #endregion

        #region Methods (ToString)

        public override string ToString()
        {
            return this.Title;
        }

        #endregion

        #region Methods (Helper)

        public string GetValueOrEmpty(string key)
        {
            if (Dictionary.ContainsKey(key))
            {
                return Dictionary[key];
            }
            else
            {
                return string.Empty;
            }
        }

        public string[] GetSplitOrEmpty(string key, char split)
        {
            return GetSplitOrEmpty(key, split.ToString());
        }

        public string[] GetSplitOrEmpty(string key, string split)
        {
            string value = GetValueOrEmpty(key);
            if (string.IsNullOrEmpty(value))
            {
                return new List<string>().ToArray();
            }
            else
            {
                return value.Split(new string[] { split }, StringSplitOptions.None);
            }
        }

        #endregion




    }
}
